﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Data.SqlClient;

using RISMOTAXDP.EmailService.MailProcess;

namespace RISMOTAXDP.EmailService
{
    /// <summary>
    /// 邮件创建线程
    /// </summary>
    public class MailCreateThread : IDisposable
    {
        /// <summary>
        /// 线程对象
        /// </summary>
        private Thread m_Thread;

        /// <summary>
        /// 邮件处理类
        /// </summary>
        private List<IMailProcess> m_Processes;


        /// <summary>
        /// 前置邮件处理类
        /// </summary>
        private MailForwardProcess m_MailForwardProcess;


        

        /// <summary>
        /// 初始化
        /// </summary>
        public MailCreateThread()
        {
            //1、创建邮件处理程序
            m_MailForwardProcess = new MailForwardProcess();
            m_Processes = new List<IMailProcess>();
            m_Processes.Add(new MailTrialAccountPasswordNotifyProcess());
            m_Processes.Add(new MailAccountPasswordNotifyProcess());
            m_Processes.Add(new MailAccountResetPasswordNotifyProcess());
            m_Processes.Add(new MailTrialAccountExpireNotifyProcess());
            m_Processes.Add(new MailAccountExpireNotifyProcess());

            m_Processes.Add(new MailTaxLawSpecialExpressNotifyProcess());


            //2、创建线程
            m_Thread = new Thread(new ThreadStart(ThreadRun));

        }


        /// <summary>
        /// 启动线程
        /// </summary>
        public void Start()
        {
            //1、启动线程
            if (State == ThreadState.Stopped)
            {
                m_Thread = new Thread(new ThreadStart(ThreadRun));
            }
            if (State == ThreadState.Unstarted)
            {
                m_Thread.Start();
            }
        }

        /// <summary>
        /// 停止线程
        /// </summary>
        public void Stop()
        {
            //1、停止线程
            try
            {

                m_Thread.Interrupt();
                if (m_Thread.ThreadState != ThreadState.Stopped)
                {
                    m_Thread.Join();
                }
            }
            catch { }
        }



        /// <summary>
        /// 邮件创建处理
        /// </summary>
        private void ThreadRun()
        {
            while (true)
            {

                //1、检查系统执行状态

                if (GlobalObject.State == ServiceState.Stopped)
                {
                    break;
                }


                switch (GlobalObject.State)
                {
                    case ServiceState.Stopped:
                        break;
                        
                    case ServiceState.Running:
                        //创建数据库连接
                        SqlConnection conn = GlobalObject.CreateConnect();
                        if (conn != null)
                        {

                            if (GlobalObject.SystemInfo.TraceMailCreate)
                            {
                                GlobalObject.WriteSystemLog("T81000001", null);
                            }

                            //执行获取前置邮件处理
                            m_MailForwardProcess.Process(conn);

                            if (GlobalObject.SystemInfo.TraceMailCreate)
                            {
                                GlobalObject.WriteSystemLog("T81000002", null);
                            }


                            if (GlobalObject.SystemInfo.TraceMailCreate)
                            {
                                GlobalObject.WriteSystemLog("T82000001", null);
                            }
                             
                            //调用邮件生成处理
                            for (int i = 0; i < m_Processes.Count; i++)
                            {
                                if (!CanContinue(conn)) break;
                                if (m_Processes[i].SetParameters(conn))
                                {
                                    int mailCreateCount = m_Processes[i].CheckData();

                                    //执行邮件生成
                                    for (int mailIndex = 0; mailIndex < mailCreateCount; mailIndex++)
                                    {
                                        if (!CanContinue(conn)) break;
                                        try
                                        {
                                            m_Processes[i].Process(mailIndex);
                                        }
                                        catch (Exception ex)
                                        {
                                            GlobalObject.WriteOperationLog("E81000005", ex, m_Processes[i].GetMailOPCode(), mailIndex + 1);
                                        }
                                    }


                                }

                            }
                            

                            if (GlobalObject.SystemInfo.TraceMailCreate)
                            {
                                GlobalObject.WriteSystemLog("T82000002", null);
                            }


                            //关闭数据库连接
                            GlobalObject.CloseConnect(conn);

                        }

                        break;
                    case ServiceState.Paused:

                        break;


                }

                //指定当前线程等待
                if (GlobalObject.State != ServiceState.Stopped)
                {

                    try
                    {
                        Thread.Sleep(GlobalObject.SystemInfo.MailCreateInterval * 1000);
                    }
                    catch { }
                }



            }

        }

        /// <summary>
        /// 检查系统状态以及数据库连接状态
        /// </summary>
        /// <param name="conn">数据库连接</param>
        /// <returns>返回是否可继续</returns>
        private bool CanContinue(SqlConnection conn)
        {
            return GlobalObject.State == ServiceState.Running && conn.State != System.Data.ConnectionState.Closed;
        }

        public System.Threading.ThreadState State
        {
            get
            {
                return m_Thread.ThreadState;
            }
        }

        #region IDisposable 成员

        public void Dispose()
        {
            //1、清理线程
            m_Thread = null;

            //2、清理邮件处理程序
            while (m_Processes.Count > 0)
            {
                m_Processes[0].Dispose();
                m_Processes.RemoveAt(0);
            }

        }

        #endregion
    }
}
